'use strict';

const Service = require('egg').Service;

class TopicService extends Service {
  async insertTopic(topic) {
    const { ctx } = this;
    return await ctx.model.Topic.create(topic);
  }

  async insertDiscuss(discuss) {
    const { ctx } = this;
    return await ctx.model.Discuss.create(discuss);
  }

  async queryTopicCounts(query) {
    const { ctx } = this;
    return await ctx.model.Topic.findAndCountAll({
      where: query,
      order: [[ 'created_at', 'DESC' ]],
    });
  }

  async queryTopicDetail(query) {
    const { ctx } = this;
    return await ctx.model.Topic.findOne({
      where: query,
    });
  }

  async queryTopicList(query) {
    const { ctx } = this;
    return await ctx.model.Topic.findAll({
      where: query,
      order: [[ 'created_at', 'DESC' ]],
    });
  }

  async topicDetailHandler(topicId) {
    const { ctx, service } = this;
    const topic = await ctx.service.topic.queryTopicDetail({
      topicId,
    });
    const userId = topic.userId;
    const user = await service.user.getUserByUserId(userId);

    // TODO: 获取评论、点赞信息
    const comments = await this.queryComments({
      topicId,
    });
    const thumbsUpStatus = await this.queryThumbsUp({
      topicId,
      userId: ctx.user.userId,
      status: 1,
    });

    const thumbs_up = await this.queryThumbsUp({
      topicId,
      status: 1,
    });

    const topicDetail = {
      userInfo: {
        username: user.username,
        avatarUrl: user.avatarUrl,
        userId: user.userId,
      },
      topic,
      comments,
      thumbs_up: {
        total: thumbs_up.count,
        status: thumbsUpStatus.count,
      },
    };
    return topicDetail;
  }

  async addThumbsUp(query, topicStatus) {
    const { ctx } = this;
    const result = await this.queryThumbsUp(query);
    if (!result.count) {
      return await ctx.model.ThumbsUp.create(topicStatus);
    }
    return await ctx.model.ThumbsUp.update(topicStatus, {
      where: query,
    });
  }

  // ==================
  async queryThumbsUp(query) {
    return await this.ctx.model.ThumbsUp.findAndCountAll({
      where: query,
    });
  }

  async queryComments(query) {
    return await this.ctx.model.Discuss.findAll({
      where: query,
      order: [[ 'created_at', 'DESC' ]],
    });
  }
}

module.exports = TopicService;
